package com.swolin.designPatter;

import java.util.ArrayList;
import java.util.List;

interface Observer{
    void update(String message);
}

class Subject{
    private List<Observer> observers = new ArrayList<Observer>();
    private String state;


    public String getState(){
        return state;
    }
    public void setState(String state){
        this.state = state;
        notifyAllObservers();
    }
    public void attach(Observer observer){
        observers.add(observer);
    }
    public void detach(Observer observer){
        observers.remove(observer);
    }
    public void notifyAllObservers(){
        for(Observer observer : observers){
            observer.update(state);
        }
    }

}
class ConcreteObserver implements Observer{
    private String name;

    public ConcreteObserver(String name){
        this.name = name;
    }

    public void update(String message) {
        System.out.println(name + "received message: " + message);
    }
}


public class ObserverPatternExample {
    public static void main(String[] args){
        Subject subject = new Subject();

        ConcreteObserver observer1 = new ConcreteObserver("observer1");
        ConcreteObserver observer2 = new ConcreteObserver("observer2");
        ConcreteObserver observer3 = new ConcreteObserver("observer3");
        subject.attach(observer1);
        subject.attach(observer2);
        subject.attach(observer3);

        subject.setState("some state");
        subject.detach(observer2);
        subject.setState("another state");
        System.out.println();
    }
}
